//License: Artistic License v2.0, http://opensource.org/licenses/Artistic-2.0

package main

import (
	"crypto/hmac"
	"crypto/sha512"
	"math/rand"
	"strconv"
	"time"
)

//EncodeString encodes a string into a random key and a hash.
//For example, this can be used to store a password.
func EncodeString(secret string) (key string, hash []byte) {
	rand.Seed(time.Now().Unix())
	key = strconv.Itoa(rand.Int())
	h := hmac.New(sha512.New, []byte(key+secret))
	hash = h.Sum(nil)
	return
}

//EncodingIsOk checks if the given string, if decoded, will match its key and hash.
//For example, this can be used to authenticate user-entered password.
func EncodingIsOk(secret, key string, hash []byte) bool {
	h := hmac.New(sha512.New, []byte(key+secret))
	s := h.Sum(nil)
	if len(s) != len(hash) {
		return false
	}
	for i := 0; i < len(s); i++ {
		if s[i] != hash[i] {
			return false
		}
	}
	return true
}

//Copyright: Slamet Hendry
